package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogAspect {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.annotation.Log)")
    public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {
//        1.获取日志对象信息
//        1.1操作员工ID
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer operateEmpId = (Integer) claims.get("id");
//        1.2操作时间
        LocalDateTime operateTime = LocalDateTime.now();
//        1.3操作类名
        String className = pjp.getTarget().getClass().getName();
//        1.4操作方法名
        String methodName = pjp.getSignature().getName();
//        1.5方法参数
        Object[] args = pjp.getArgs();
        String methodParams = Arrays.toString(args);
//        1.6返回值
        long begin = System.currentTimeMillis();
        Object result = pjp.proceed();
        String returnValue = result.toString();
//        1.7花费时间
        long end = System.currentTimeMillis();
        long costTime = end - begin;

//        2.封装成对象
        OperateLog operateLog = new OperateLog(null, operateEmpId, operateTime, className,
                                                methodName, methodParams, returnValue,costTime, null);

//        3.调用Mapper层新增用户
        operateLogMapper.insert(operateLog);

        return result;

    }
}
